package com.yulongtian.offers.day202301;

/**
 * https://leetcode.cn/problems/add-two-numbers/
 * 可
 *
 * @author yulongTian
 * @create 2023-01-31 14:02
 */
public class Test05 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(5);
        ListNode l2 = new ListNode(5);
        ListNode res = addTwoNumbers(l1, l2);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int len1 = 0;
        int len2 = 0;
        //遍历两个链表，获得长度，然后保证l1长  l2短
        ListNode p1 = l1;
        while (p1 != null) {
            len1++;
            p1 = p1.next;
        }
        p1 = l2;
        while (p1 != null) {
            len2++;
            p1 = p1.next;
        }
        //保证l1长度大于等于l2
        if (len2 > len1) {
            ListNode temp = l1;
            l1 = l2;
            l2 = temp;
        }

        //l1和l2指针
        p1 = l1;
        ListNode p2 = l2;
        //p1和p2同步前进，pre为p1和p2的前一个指针
        ListNode pre = p1;

        //进位
        int c = 0;

        //直到p2遍历结束
        while (p2 != null) {
            int a = p1.val;
            int b = p2.val;
            //某位相加结果的个位
            p1.val = (a + b + c) % 10;
            //进位
            c = (a + b + c) / 10;
            //指针移动
            pre = p1;
            p1 = p1.next;
            p2 = p2.next;
        }
        //进位不为0，还需要新键节点存放进位
        while (c != 0) {
            if (p1 == null) {
                pre.next = new ListNode(c);
                break;
            }
            int a = p1.val;
            p1.val = (a + c) % 10;
            c = (a + c) / 10;

            pre = p1;
            p1 = p1.next;
        }
        return l1;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
